package com.sdhs.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.sdhs.common.core.domain.entity.SysUser;
import com.sdhs.system.domain.SysNotice;
import com.sdhs.system.mapper.SysNoticeMapper;
import com.sdhs.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.sdhs.common.enums.MessageInfoDictEnum;
import com.sdhs.common.utils.DateUtils;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.common.utils.StringUtils;
import com.sdhs.system.domain.MessageInfoDO;
import com.sdhs.system.domain.dto.MessageInfoDTO;
import com.sdhs.system.domain.dto.MessageInfoReadDTO;
import com.sdhs.system.domain.vo.MessageInfoVO;
import com.sdhs.system.mapper.MessageInfoMapper;
import com.sdhs.system.service.IMessageInfoReadService;
import com.sdhs.system.service.IMessageInfoService;

import cn.hutool.core.bean.BeanUtil;

/**
 * 消息Service业务层处理
 *
 * @author mz
 * @date 2023-09-04
 */
@Service
public class MessageInfoServiceImpl implements IMessageInfoService {
	
    @Autowired
    private MessageInfoMapper messageInfoMapper;
    
    @Autowired
    private IMessageInfoReadService iMessageInfoReadService;

    @Autowired
    private SysNoticeMapper noticeMapper;
    @Autowired
    private SysUserMapper userMapper;

    /**
     * 查询消息
     *
     * @param id 消息主键
     * @return 消息
     */
    @Override
    public MessageInfoVO selectMessageInfoById(Long id) {
        MessageInfoVO messageInfoVO = messageInfoMapper.selectMessageInfoById(id);
        // 如果是未读，变更状态为已读
        if (messageInfoVO.getStatus().equals(MessageInfoDictEnum.READ_FLAG__UN_READ.getCode())) {
            messageInfoVO.setStatus(MessageInfoDictEnum.READ_FLAG__READ.getCode());
            MessageInfoDO messageInfoDO = BeanUtil.copyProperties(messageInfoVO, MessageInfoDO.class);
            messageInfoMapper.updateMessageInfo(messageInfoDO);
            // 增加阅读记录
            MessageInfoReadDTO messageInfoRead = new MessageInfoReadDTO()
                    .setTaskId(messageInfoDO.getTaskId())
                    .setReadTime(new Date())
                    .setReaderUserName(SecurityUtils.getUsername())
                    .setReaderNickName(SecurityUtils.getNickName())
                    .setDeptCode(String.valueOf(SecurityUtils.getDeptId()))
                    .setDeptName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
//                    .setCompanyId(SecurityUtils.getLoginDept().getCompanyId().toString())
//                    .setCompanyName(SecurityUtils.getLoginDept().getCompanyName());
            iMessageInfoReadService.insertMessageInfoRead(messageInfoRead);
        }
        return messageInfoVO;
    }
    /**
     * 查询安全项目消息
     *
     * @param id 消息主键
     * @return 消息
     */
    @Override
    public MessageInfoVO selectMessageInfoByNoticeId(Long id) {
         MessageInfoVO messageInfoVO = messageInfoMapper.selectMessageInfoByNoticeId(id);
        /*将通知状态改为已读*/
        SysNotice sysNotice = new SysNotice();
        sysNotice.setStatus("1");
        sysNotice.setNoticeId(id);
        noticeMapper.updateNotice(sysNotice);
        return messageInfoVO;
    }
    /**
     * 查询消息列表
     *
     * @param messageInfoDTO 消息
     * @return 消息
     */
    @Override
    public List<MessageInfoVO> selectMessageInfoList(MessageInfoDTO messageInfoDTO) {
        messageInfoDTO.setDelFlag("0");
        messageInfoDTO.setReceiverUserName(SecurityUtils.getUsername());
        List<MessageInfoVO> messageInfos = messageInfoMapper.selectMessageInfoList(messageInfoDTO);
        return messageInfos;
    }

    /**
     * 新增消息
     *
     * @param messageInfo 消息
     * @return 结果
     */
    @Override
    public int insertMessageInfo(MessageInfoDO messageInfo) {
    	messageInfo.setCreateBy(SecurityUtils.getUsername());
        messageInfo.setCreateTime(DateUtils.getNowDate());
        return messageInfoMapper.insertMessageInfo(messageInfo);
    }

    /**
     * 修改消息
     *
     * @param messageInfo 消息
     * @return 结果
     */
    @Override
    public int updateMessageInfo(MessageInfoDO messageInfo) {
    	messageInfo.setUpdateBy(SecurityUtils.getUsername());
        messageInfo.setUpdateTime(DateUtils.getNowDate());
        return messageInfoMapper.updateMessageInfo(messageInfo);
    }

    /**
     * 批量删除消息
     *
     * @param ids 需要删除的消息主键
     * @return 结果
     */
    @Override
    public int deleteMessageInfoByIds(Long[] ids) {
        return messageInfoMapper.deleteMessageInfoByIds(ids);
    }

    /**
     * 删除消息信息
     *
     * @param id 消息主键
     * @return 结果
     */
    @Override
    public int deleteMessageInfoById(Long id) {
        return messageInfoMapper.deleteMessageInfoById(id);
    }


    @Override
    public int updateAllMsg(String status) {
        MessageInfoDO messageInfo = new MessageInfoDO();
        messageInfo.setReceiveTime(new Date());
        messageInfo.setStatus(status);
        messageInfo.setReceiverUserName(SecurityUtils.getUsername());
         int i = messageInfoMapper.updateAllMsg(messageInfo);
        /*将通知状态改为已读*/
        SysNotice sysNotice = new SysNotice();
        sysNotice.setStatus("1");
        SysUser sysUser = userMapper.selectUserByName(SecurityUtils.getUsername());
        sysNotice.setUserId(sysUser.getUserId());
        noticeMapper.updateNoticeBuyName(sysNotice);
        return i;
    }

    /**
     * 发送消息
     *
     * @param messageInfoDTO 系统消息
     * @return 结果
     */
//    @Override
//    public void sendMsg(MessageInfoDTO messageInfoDTO) {
//        R<SysUser> sysUserR = remoteUserService.selectUserByUserName(SecurityUtils.getUsername());
//        // 系统消息
//        List<String> receiverIdList = messageInfoDTO.getReceiverIdList();
//        R<List<UserDict>> userDictResult = remoteUserService.translateUserId(receiverIdList);
//        if (ObjectUtils.allNotNull(userDictResult, userDictResult.getData())) {
//            userDictResult.getData().forEach(item -> this.baseMapper.insert(new MessageInfoDO()
//                    .setTitle(messageInfoDTO.getTitle())
//                    .setContent(messageInfoDTO.getContent())
//                    .setSenderUserName(SecurityUtils.getUsername())
//                    .setSenderNickName(sysUserR.getData().getNickName())
//                    .setReceiverNickName(item.getNickName())
//                    .setReceiverUserName(item.getNickName())
//                    .setSendTime(new Date())
//                    .setStatus(MessageInfoDictEnum.READ_FLAG__UN_READ.getCode())
//                    .setTaskId(messageInfoDTO.getTaskId())
//                    .setType(messageInfoDTO.getType())
//            ));
//        }
//    }
    
    /**
     * 获取消息列表
     * @param title
     * @param content
     * @param userNames 多个用,分割
     * @return
     */
    @Override
    public List<MessageInfoDO> getMsgList(String title, String content, Long taskId, String type, String userNames) {
    	List<MessageInfoDO> list = new ArrayList<MessageInfoDO>();
    	if (StringUtils.isNotBlank(userNames)) {
    		String[] userNameArray = userNames.split(",");
    		list = getMsgList(title, content, taskId, type, Arrays.asList(userNameArray));
    	}
    	return list;
    }
    
    /**
     * 获取消息列表
     * @param title
     * @param content
     * @param userNameList
     * @return
     */
    @Override
    public List<MessageInfoDO> getMsgList(String title, String content, Long taskId, String type, List<String> userNameList) {
    	List<MessageInfoDO> list = new ArrayList<MessageInfoDO>();
    	if (!CollectionUtils.isEmpty(userNameList)) {
    		Date date = new Date();
    		for (String userName : userNameList) {
    			list.add(new MessageInfoDO()
    					.setTitle(title)
                        .setContent(content)
                        .setSenderUserName("system")
                        .setSenderNickName("系统消息")
                        .setReceiverUserName(userName)
                        .setSendTime(date)
                        .setStatus(MessageInfoDictEnum.READ_FLAG__UN_READ.getCode())
                        .setTaskId(taskId)
                        .setIsHandle("0")
                        .setType(type)
                        .setDelFlag("0")
                        );
    		}
    	}
    	return list;
    }
    
    /**
     * 批量发送消息（我的消息）
     * @param entityList
     */
    @Override
    public void sendMsgBatch(List<MessageInfoDO> entityList) {
    	if (!CollectionUtils.isEmpty(entityList)) {
    		messageInfoMapper.insertMessageInfoBatch(entityList);
    	}
    }
    
    /**
     * 查询某个用户是否收到某个消息
     * @return
     */
    public Integer countByContent(String title, String content, String receiverUserName) {
    	return messageInfoMapper.countByContent(title, content, receiverUserName);
    }
    
}







